package com.xieshue.im.server.handler;

import com.xieshue.im.protocol.Command;
import com.xieshue.im.protocol.Message;
import com.xieshue.im.protocol.MessageProto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xieshue
 * @date 2017\12\12 0012
 */
public class ImServerChannelHandler extends ChannelHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ImServerChannelHandler.class);

    private Map<String, Channel> channels = new ConcurrentHashMap<>();

    /**
     * 空闲事件触发与IdleStateHandler 联合使用
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                throw new Exception("idle exception");
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String id = ctx.channel().id().toString();
        channels.put(id, ctx.channel());
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("服务接收客服端信息中...");
        }
        String cid = ctx.channel().id().toString();
        System.out.println(cid);
        if (msg instanceof MessageProto) {
            MessageProto messageProto = (MessageProto) msg;
            if (messageProto.getCommand() == Command.PING) {
                //客户端发出的心跳请求
                System.out.println(
                        ctx.channel().remoteAddress() + "->Server :\n" + messageProto.getMessage().getBody()
                );
            } else if (messageProto.getCommand() == Command.LOGIN) {
                //客户端发出的登录请求
                System.out.println(messageProto.getMessage().getBody());
                MessageProto messageResp = MessageProto.newBuilder()
                        .setCommand(Command.LOGIN)
                        .setMessage(Message.newBuilder().setBody("收到..."))
                        .build();
                ctx.writeAndFlush(messageResp);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String cid = ctx.channel().id().toString();
        logger.warn("close:{channel:'" + cid + "'}" + cause.getMessage());
        ctx.close();
    }
}
